import { getToken } from '@/utils/auth'

class WebSocketClient {
  constructor() {
    this.ws = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 3000
    this.handlers = new Map()
  }

  connect(auctionId) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      return
    }

    const token = getToken()
    const wsUrl = process.env.VUE_APP_WS_API + '/websocket/auction/' + auctionId + '?token=' + token
    
    this.ws = new WebSocket(wsUrl)

    this.ws.onopen = () => {
      console.log('WebSocket连接已建立')
      this.reconnectAttempts = 0
    }

    this.ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data)
        this.handleMessage(data)
      } catch (error) {
        console.error('处理WebSocket消息失败:', error)
      }
    }

    this.ws.onclose = () => {
      console.log('WebSocket连接已关闭')
      this.reconnect(auctionId)
    }

    this.ws.onerror = (error) => {
      console.error('WebSocket错误:', error)
    }
  }

  reconnect(auctionId) {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.log('达到最大重连次数')
      return
    }

    this.reconnectAttempts++
    console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
    
    setTimeout(() => {
      this.connect(auctionId)
    }, this.reconnectInterval)
  }

  disconnect() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
  }

  addMessageHandler(type, handler) {
    this.handlers.set(type, handler)
  }

  removeMessageHandler(type) {
    this.handlers.delete(type)
  }

  handleMessage(data) {
    const handler = this.handlers.get(data.type)
    if (handler) {
      handler(data)
    }
  }
}

export default new WebSocketClient() 